<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #box {
        position: absolute;
        top: 20px;
        left: 100px;
        width: 100px;
        height: 100px;
        background-color: skyblue;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>

    <script>
      function animation(ele, cssObj, duration) {
        var time = 20; //每隔20秒移动一次
        var stepContent = duration / time; //总共移动的次数
        var oldCssStyle = {}; //获得原先样式表
        var content = 0;
        var clock;
        var movelength = {};
        for (var keystyle in cssObj) {
          //从cssObj中获得所有所需要的key
          oldCssStyle[keystyle] = parseInt(
            window.getComputedStyle(ele, null)[keystyle] //在从样式表中找到相关key所对应的值
          );

          // console.log(oldCssStyle[keystyle]);
        }
        console.log(oldCssStyle);
        for (var keystyle in cssObj) {
          // console.log(parseInt(cssObj[keystyle]));
          movelength[keystyle] =
            (parseInt(cssObj[keystyle]) - oldCssStyle[keystyle]) / stepContent; //需要移动的长度
        }
        // console.log(movelength);
        clock = setInterval(function () {
          content++;
          //元素开始移动
          for (var keystyle in cssObj) {
            ele.style[keystyle] =
              movelength[keystyle] * content + oldCssStyle[keystyle] + 'px';
            // console.log(content);
          }

          // console.log(ele.style[keystyle]);
          if (content >= stepContent) {
            //当到达终点时停止
            // console.log(1);
            clearInterval(clock);
            for (var keystyle in cssObj) {
              ele.style[keystyle] = cssObj[keystyle];
            }
          }
        }, time);
      }

      var box = document.getElementById('box');
      box.addEventListener('click', function () {
        animation(box, { left: '0px', top: 0 }, 1800);
      });
    </script>
  </body>
</html>
